<template>
  <div class="status-container">
    <NavIndex />
    <div class="content-wrapper">
      <!-- Left section -->
      <div class="section left-section">
        <div class="chart-container">
          <div ref="studyTimeChart" class="chart"></div>
        </div>
        <div class="chart-container">
          <div ref="studyTypeChart" class="chart"></div>
        </div>
        <div class="chart-container">
          <div ref="weeklyTrendChart" class="chart"></div>
        </div>
      </div>
      
      <!-- Center section -->
      <div class="section center-section">
        <div class="camera-container">
          <h3 class="camera-title">摄像头监测</h3>
          
          <div v-if="!cameraActive && !capturedImage" class="camera-access">
            <div class="camera-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#888888" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path>
                <circle cx="12" cy="13" r="4"></circle>
                <circle cx="12" cy="13" r="1.5" fill="#888888"></circle>
                <path d="M17 8.5v1"></path>
              </svg>
            </div>
            <p class="camera-message">需要访问您的摄像头</p>
            <button @click="startCamera" class="camera-button">允许访问</button>
          </div>
          
          <div v-if="cameraActive && !capturedImage" class="camera-view">
            <img src="@/assets/img/模拟相片.jpg" alt="Static face" class="static-face" />
            <div class="camera-controls">
              <button @click="captureImage" class="capture-button">
                <span class="capture-icon"></span>
              </button>
            </div>
          </div>
          
          <div v-if="capturedImage" class="captured-view">
            <div class="captured-image-container">
              <img src="@/assets/img/模拟相片.jpg" alt="Captured" class="captured-image">
              <div class="face-detection" :style="faceDetectionStyle"></div>
            </div>
            
            <div class="analysis-controls">
              <button @click="resetCamera" class="reset-button">重新拍照</button>
              <button v-if="!mentalAnalysisResult" @click="analyzeImage" class="analyze-button camera-analyze">分析状态</button>
            </div>
            
            <div v-if="mentalAnalysisResult" class="mental-analysis">
              <h4>精神状态分析</h4>
              <div class="analysis-result-list">
                <div v-for="(item, index) in mentalAnalysisResult" :key="index" class="analysis-item">
                  <div class="analysis-feature">{{ item.feature }}:</div>
                  <div class="analysis-description">{{ item.description }}</div>
                </div>
              </div>
              <div class="analysis-conclusion">
                综合评分: <span :class="'score-' + overallScore">{{ overallScore }}/10</span>
                <div class="conclusion-text">{{ analysisConclusion }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Right section -->
      <div class="section right-section">
        <div class="recommended-content">
          <h3>推荐学习内容</h3>
          <div class="scrollable-content">
            <div v-for="(item, index) in recommendedContent" :key="index" class="content-item" @click="handleContentClick(item.title)" style="cursor:pointer;">
              <div class="content-header">
                <div class="content-title">{{ item.title }}</div>
                <div class="content-tag">{{ item.tag }}</div>
              </div>
              <div class="content-description">{{ item.description }}</div>
            </div>
          </div>
        </div>
        
        <div class="study-analysis">
          <h3>学习状态分析</h3>
          <p>本周学习进度： {{ studyProgress }}%</p>
          <div class="progress-bar">
            <div class="progress" :style="{width: studyProgress + '%'}"></div>
          </div>
          <button @click="analyzeStudyStatus" class="analyze-button">分析学习状态</button>
          <div v-if="studyAnalysisResult" class="analysis-result">
            {{ studyAnalysisResult }}
          </div>
        </div>
        
        <div class="skill-radar">
          <div ref="skillRadarChart" class="chart radar-chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import * as echarts from 'echarts';
import NavIndex from "@/components/topNav/topNavIndex.vue";
import { useRouter } from 'vue-router';
import { learningRouteMap } from '@/views/learning/index.ts';

// Chart references
const studyTimeChart = ref(null);
const studyTypeChart = ref(null);
const weeklyTrendChart = ref(null);
const skillRadarChart = ref(null);

// Chart instances
let chartInstances = [];

// Study progress and analysis
const studyProgress = ref(75);
const studyAnalysisResult = ref(null); // 学习状态分析结果
const mentalAnalysisResult = ref(null); // 精神状态分析结果

// Sample data
const studyTimeData = {
  categories: ['总时长', '周时长', '假期时长', '工作日时长'],
  values: [120, 35, 60, 25]
};

const studyTypeData = [
  { value: 30, name: 'Java后端' },
  { value: 25, name: '前端' },
  { value: 15, name: '数据库' },
  { value: 10, name: '算法' },
  { value: 8, name: 'PS' },
  { value: 7, name: '视频剪辑' },
  { value: 5, name: '其他' }
];

const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
const weeklyTrendData = [2.5, 3.2, 4.0, 2.8, 3.5, 5.2, 4.8];

const skillData = studyTypeData.map(item => ({
  name: item.name,
  value: Math.floor(item.value * 2.5) // Scale to 0-100 range for radar chart
}));

// Recommended content - add more items to test scrolling
const recommendedContent = reactive([
  {
    title: 'Vue.js 高级组件设计',
    description: '学习如何设计可复用的Vue组件和高效状态管理',
    tag: '前端'
  },
  {
    title: 'Spring Boot微服务架构',
    description: '从零开始构建微服务架构应用',
    tag: 'Java后端'
  },
  {
    title: 'MySQL性能优化实战',
    description: '数据库索引设计和查询优化技巧',
    tag: '数据库'
  },
  {
    title: '数据结构与算法：从入门到精通',
    description: '掌握常见算法和解题技巧',
    tag: '算法'
  },
  {
    title: 'Photoshop创意设计',
    description: '学习UI设计和图像处理技巧',
    tag: 'PS'
  },
  {
    title: 'Adobe Premiere视频剪辑教程',
    description: '从基础到高级的视频剪辑技术',
    tag: '视频剪辑'
  },
  {
    title: 'Java并发编程实践',
    description: '掌握Java多线程和并发处理的核心技术',
    tag: 'Java后端'
  },
  {
    title: 'React Hooks与状态管理',
    description: '现代React应用开发与状态管理模式',
    tag: '前端'
  }
]);

// Camera functionality
const cameraActive = ref(false);
const capturedImage = ref(null);
const videoElement = ref(null);
const overallScore = ref(0);
const stream = ref(null);

// Face detection style (mock position)
const faceDetectionStyle = computed(() => {
  return {
    left: '50%',
    top: '50%',
    width: '200px',
    height: '250px',
    transform: 'translate(-50%, -50%)'
  };
});

// Analysis conclusion based on score
const analysisConclusion = computed(() => {
  if (overallScore.value >= 8) {
    return '您的精神状态非常好，保持这种状态将有助于学习效率。';
  } else if (overallScore.value >= 6) {
    return '您的精神状态良好，但有轻微疲劳迹象，建议适当休息。';
  } else if (overallScore.value >= 4) {
    return '您的精神状态一般，建议调整作息，增加休息时间。';
  } else {
    return '您的精神状态较差，建议立即休息，避免长时间学习。';
  }
});

// Initialize charts
onMounted(() => {
  // Study Time Bar Chart
  const timeChartInstance = echarts.init(studyTimeChart.value);
  timeChartInstance.setOption({
    title: {
      text: '个人学习时长统计(小时)',
      left: 'left',
      top: 5,
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '10%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 12
      }
    },
    yAxis: {
      type: 'category',
      data: studyTimeData.categories,
      axisLabel: {
        fontSize: 12
      }
    },
    series: [{
      name: '学习时长',
      type: 'bar',
      data: studyTimeData.values,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#0d63c0' }
        ])
      }
    }]
  });
  
  // Study Type Pie Chart
  const typeChartInstance = echarts.init(studyTypeChart.value);
  typeChartInstance.setOption({
    title: {
      text: '学习类型分布',
      left: 'left',
      top: 5,
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}小时 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      bottom: 10,
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontSize: 10
      },
      data: studyTypeData.map(item => item.name)
    },
    series: [{
      name: '学习类型',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['55%', '55%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: studyTypeData
    }]
  });
  
  // Weekly Trend Line Chart
  const trendChartInstance = echarts.init(weeklyTrendChart.value);
  trendChartInstance.setOption({
    title: {
      text: '一周学习时长趋势',
      left: 'left',
      top: 5,
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '8%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: weekdayLabels,
      axisLabel: {
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}小时',
        fontSize: 12
      }
    },
    series: [{
      name: '学习时长',
      type: 'line',
      data: weeklyTrendData,
      smooth: true,
      lineStyle: {
        width: 3,
        shadowColor: 'rgba(0,0,0,0.3)',
        shadowBlur: 10,
        shadowOffsetY: 8
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(128, 255, 165, 0.8)' },
          { offset: 1, color: 'rgba(1, 191, 236, 0.1)' }
        ])
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 20,
          shadowColor: 'rgba(0,0,0,0.5)'
        }
      }
    }]
  });
  
  // Skill Radar Chart
  const radarChartInstance = echarts.init(skillRadarChart.value);
  
  // Prepare indicator data for radar chart
  const indicators = studyTypeData.map(item => ({
    name: item.name,
    max: 100
  }));
  
  // Prepare series data for radar chart
  const radarData = [
    {
      value: skillData.map(item => item.value),
      name: '技能水平',
      areaStyle: {
        color: 'rgba(255, 228, 52, 0.6)'
      }
    }
  ];
  
  radarChartInstance.setOption({
    title: {
      text: '技能蛛网图',
      left: 'left',
      top: 5,
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {},
    radar: {
      indicator: indicators,
      shape: 'polygon',
      splitNumber: 5,
      radius: '65%',
      center: ['55%', '55%'],
      axisName: {
        color: '#333',
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          color: [
            'rgba(238, 197, 102, 0.1)', 'rgba(238, 197, 102, 0.2)',
            'rgba(238, 197, 102, 0.4)', 'rgba(238, 197, 102, 0.6)',
            'rgba(238, 197, 102, 0.8)', 'rgba(238, 197, 102, 1)'
          ].reverse()
        }
      },
      splitArea: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(238, 197, 102, 0.5)'
        }
      }
    },
    series: [{
      name: '技能分布',
      type: 'radar',
      data: radarData,
      symbol: 'circle',
      symbolSize: 8
    }]
  });
  
  // Save chart instances for resize handling and cleanup
  chartInstances = [
    timeChartInstance,
    typeChartInstance,
    trendChartInstance,
    radarChartInstance
  ];
  
  // Handle window resize
  window.addEventListener('resize', handleResize);
});

// Study status analysis function
const analyzeStudyStatus = () => {
  // Calculate total time
  const totalTime = studyTimeData.values[0];
  
  // Calculate days in week with significant study time (more than 1 hour)
  const effectiveDays = weeklyTrendData.filter(time => time > 1).length;
  
  // Calculate average time per day
  const avgTimePerDay = totalTime / 7;
  
  // Analysis logic
  let result = '';
  
  if (avgTimePerDay > 4) {
    result = '您的学习状态非常优秀！保持高强度的学习节奏，知识积累正在加速。';
  } else if (avgTimePerDay > 2) {
    result = '您的学习状态良好，每天有稳定的学习时间，继续保持！';
  } else if (effectiveDays >= 5) {
    result = '您的学习较为规律，但每天时间偏短，建议适当增加单次学习时长。';
  } else if (effectiveDays >= 3) {
    result = '您的学习时间分布不均，有几天学习强度高，但整体不够稳定。';
  } else {
    result = '您的学习时间不足，建议制定更规律的学习计划并严格执行。';
  }
  
  studyAnalysisResult.value = result;
};

// Handle chart resize
const handleResize = () => {
  chartInstances.forEach(chart => {
    chart.resize();
  });
};

// Start camera - simplified version
const startCamera = () => {
  cameraActive.value = true;
};

// Capture image - simplified version
const captureImage = () => {
  capturedImage.value = '@/assets/img/模拟相片.jpg';
  cameraActive.value = false;
};

// Analyze image
const analyzeImage = () => {
  // Mock analysis result
  overallScore.value = 8;
  mentalAnalysisResult.value = [
    { feature: '面部表情', description: '自然平和，无紧张迹象' },
    { feature: '眼神状态', description: '沉稳有神，注意力集中' },
    { feature: '整体神态', description: '放松自然，精神状态良好' },
    { feature: '情绪表现', description: '平静稳定，无明显波动' }
  ];
};

// Reset camera
const resetCamera = () => {
  capturedImage.value = null;
  mentalAnalysisResult.value = null;
  startCamera();
};

// Clean up event listeners and chart instances
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chartInstances.forEach(chart => {
    chart.dispose();
  });
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop());
  }
});

const router = useRouter();

// 推荐内容点击跳转
const handleContentClick = (title) => {
  const route = learningRouteMap.find(item => item.title === title);
  if (route) {
    router.push(route.path);
  }
};
</script>

<style scoped>
.status-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f7fa;
  padding-top: 70px; /* Account for the fixed header */
}

.content-wrapper {
  display: flex;
  height: calc(100vh - 70px);
  padding: 20px;
}

.section {
  height: 100%;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  background-color: white;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.left-section {
  width: 32%;
}

.center-section {
  width: 36%;
  margin: 0 12px;
  justify-content: center;
  align-items: center;
}

.right-section {
  width: 32%;
}

.chart-container {
  flex: 1;
  margin-bottom: 15px;
  position: relative;
  min-height: calc(33% - 15px);
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 250px;
}

.radar-chart {
  width: 100%;
  height: 100%;
}

/* Camera section styles */
.camera-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.camera-title {
  width: 100%;
  text-align: left;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.camera-access {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
  width: 80%;
}

.camera-icon {
  width: 80px;
  height: 80px;
  margin-bottom: 10px;
  opacity: 0.7;
}

.camera-icon svg {
  width: 100%;
  height: 100%;
}

.camera-message {
  margin: 15px 0;
  color: #666;
}

.camera-button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.camera-button:hover {
  background-color: #2980b9;
}

.camera-view {
  width: 90%;
  height: 60%;
  position: relative;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.camera-controls {
  position: absolute;
  bottom: 15px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
}

.capture-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  border: 3px solid white;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.capture-button:hover {
  background-color: rgba(255, 255, 255, 1);
}

.capture-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: white;
  border: 2px solid #ccc;
}

.captured-view {
  width: 90%;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.captured-image-container {
  position: relative;
  width: 100%;
  height: 60%;
  border-radius: 8px;
  overflow: hidden;
  background-color: #000;
}

.captured-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.face-detection {
  position: absolute;
  border: 3px solid #2ecc71;
  box-shadow: 0 0 0 2px rgba(46, 204, 113, 0.6), 0 0 10px rgba(46, 204, 113, 0.3);
  border-radius: 6px;
}

.analysis-controls {
  display: flex;
  justify-content: space-around;
  margin: 15px 0;
}

.reset-button, .camera-analyze {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.reset-button {
  background-color: #e74c3c;
  color: white;
}

.reset-button:hover {
  background-color: #c0392b;
}

.mental-analysis {
  background-color: #f8f8f8;
  border-radius: 8px;
  padding: 15px;
  flex: 1;
  overflow-y: auto;
}

.mental-analysis h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 5px;
}

.analysis-result-list {
  margin-bottom: 15px;
}

.analysis-item {
  display: flex;
  margin-bottom: 8px;
}

.analysis-feature {
  font-weight: bold;
  width: 80px;
  flex-shrink: 0;
}

.analysis-description {
  color: #555;
}

.analysis-conclusion {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 4px;
  font-size: 13px;
}

.score-10, .score-9, .score-8 {
  color: #27ae60;
  font-weight: bold;
}

.score-7, .score-6, .score-5 {
  color: #f39c12;
  font-weight: bold;
}

.score-4, .score-3, .score-2, .score-1, .score-0 {
  color: #e74c3c;
  font-weight: bold;
}

.conclusion-text {
  margin-top: 5px;
  line-height: 1.4;
}

/* Right section styles */
.recommended-content {
  flex: 0.6;
  margin-bottom: 15px;
}

h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 5px;
}

.scrollable-content {
  height: calc(100% - 35px);
  overflow-y: auto;
  padding-right: 5px;
  max-height: 200px;
}

.content-item {
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 6px 8px;
  margin-bottom: 4px;
  border-left: 3px solid #3498db;
  transition: all 0.2s ease;
}

.content-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
}

.content-title {
  font-weight: 600;
  font-size: 12px;
  margin-bottom: 3px;
  color: #2c3e50;
}

.content-description {
  font-size: 10px;
  color: #666;
  margin-bottom: 3px;
  line-height: 1.2;
}

.content-tag {
  display: inline-block;
  background-color: #e1f0ff;
  color: #3498db;
  padding: 1px 5px;
  border-radius: 10px;
  font-size: 9px;
}

.study-analysis {
  flex: 0.8;
  margin-bottom: 15px;
}

.progress-bar {
  height: 6px;
  background-color: #f0f0f0;
  border-radius: 3px;
  margin: 8px 0 15px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: linear-gradient(to right, #3498db, #2ecc71);
  border-radius: 3px;
  transition: width 1s;
}

.analyze-button {
  padding: 6px 12px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 12px;
}

.analyze-button:hover {
  background-color: #2980b9;
}

.analysis-result {
  margin-top: 10px;
  padding: 8px;
  background-color: #f8f9fa;
  border-left: 3px solid #3498db;
  font-size: 12px;
  line-height: 1.4;
}

.skill-radar {
  flex: 1.6;
}

.static-face {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}
</style>
